package com.tzxs.pay.main.bill.detail;

import android.app.Activity;
import android.app.ProgressDialog;
import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.content.ComponentName;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.tzxs.pay.BR;
import com.tzxs.pay.R;
import com.tzxs.pay.databinding.CollInstaItemDetailBinding;
import com.tzxs.pay.databinding.ItemRelativeOrderBinding;
import com.tzxs.pay.main.base.BaseActivity;
import com.tzxs.pay.main.bill.detail.model.RelativeBean;
import com.tzxs.pay.main.bill.detail.refund.RefundActivity;
import com.tzxs.pay.main.bill.model.CoInDetailBean;
import com.tzxs.pay.main.bill.viewmodel.BillViewModel;
import com.tzxs.pay.main.gather.viewmodel.BankViewModel;
import com.tzxs.pay.main.print.utils.print.AidlUtil;
import com.tzxs.pay.util.ApplicationDetector;
import com.tzxs.pay.util.IAdapter;
import com.tzxs.pay.util.StatusBarColorSetter;
import com.tzxs.pay.util.SystemUtil;
import com.tzxs.pay.util.viewmodel.Callback;

import org.w3c.dom.Text;

import java.io.IOException;
import java.util.List;
import java.util.Objects;
import java.util.Set;

/**
 * 收款账单  分期账单  item 详情
 */
public class CollAndInstallDetailActivity extends BaseActivity<CollInstaItemDetailBinding> implements IAdapter.ItemNavigator<RelativeBean> {
    private ProgressDialog dialog;
    private boolean isFirst = true;//一次打印
    private BillViewModel model;
    private BankViewModel bankViewModel;
    private static final int REQUEST_CODE_QUERY_BANK_CARD_TRANSACTION = 0;
    private static final String TAG = CollAndInstallDetailActivity.class.getSimpleName();

    @Override
    protected Activity getChildActivity() {
        return this;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.coll_insta_item_detail;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        StatusBarColorSetter.setStatusBarColor(this, Color.parseColor("#FAFAFA"));
        bankViewModel = ViewModelProviders.of(this).get(BankViewModel.class);
        //初始化打印机
        AidlUtil.getInstance().initPrinter();
        dataBinding.ciDetailToolbar.setTitle("");
        setSupportActionBar(dataBinding.ciDetailToolbar);
        dataBinding.ciDetailToolbar.setNavigationOnClickListener(v -> onBackPressed());
        //退款
        dataBinding.ciDetailToolbar.setOnMenuItemClickListener(item -> {
            if (item.getItemId() == R.id.back_money) {
                Intent intent = new Intent(CollAndInstallDetailActivity.this, RefundActivity.class);
                intent.putExtra("orderId", dataBinding.ciDetailOrderId.getText().toString());
                startActivity(intent);
                finish();
                return true;
            }
            return false;
        });
        model = ViewModelProviders.of(this).get(BillViewModel.class);
        //从上个页面获取到账单id
        String tradeNum = getIntent().getStringExtra("orderId");

        Log.d(TAG, "onCreate: 从上个页面获取订单号:tradeNum" + tradeNum);
        dataBinding.setViewModel(model);
        model.getCollectionBillDetail(tradeNum, () -> {
            dialog.dismiss();
            if (getIntent().getBooleanExtra("needPrint", false) && model.coInBean.get() != null) {
                print();
            }
            //根据支付状态显示不同的支付字符串
            if (model.coInBean.get() != null) {
                int status = Objects.requireNonNull(model.coInBean.get()).getPay_status();
                String orderId = Objects.requireNonNull(model.coInBean.get()).getOut_trade_no();
                if (status != 4 && status != 5 && status != 2) {
                    dataBinding.ciDetailToolbar.inflateMenu(R.menu.back_);
                }
                if (orderId.contains("tk")) {
                    dataBinding.typeTime.setText("退款时间");
                } else {
                    dataBinding.typeTime.setText("收款时间");
                }
                dataBinding.ciDetailPayStatus.setText(Objects.requireNonNull(model.coInBean.get()).getPay_status_txt());
                String payType = Objects.requireNonNull(model.coInBean.get()).getPay_user();
                switch (payType) {
                    case "微信":
                        dataBinding.ciDetailPayIcon.setImageResource(R.drawable.ic_wechat);
                        break;
                    case "支付宝":
                        dataBinding.ciDetailPayIcon.setImageResource(R.drawable.ic_alipay);
                        break;
                    default:
                        dataBinding.ciDetailPayIcon.setImageResource(R.drawable.ic_unionpay);
                        break;
                }
            } else {
                Toast.makeText(CollAndInstallDetailActivity.this, "无法查询到该订单!", Toast.LENGTH_SHORT).show();
                finish();
            }
        });
        initRelativeOrder();
        model.dialogText.observe(this, new Observer<String>() {
            @Override
            public void onChanged(@Nullable String s) {
                if (s == null) {
                    if (dialog != null) {
                        dialog.dismiss();
                    }
                } else {
                    dialog = ProgressDialog.show(CollAndInstallDetailActivity.this, s, "请稍等....", false, false);
                }
            }
        });
        model.snackbarText.observe(this, s -> {
            if (s != null) {
                Toast.makeText(CollAndInstallDetailActivity.this, s, Toast.LENGTH_SHORT).show();
            }
        });
        dataBinding.synchronizeStatusTextView.setOnClickListener(v -> {
            if (ApplicationDetector.exists(this, "com.shengpay.smartpos.shengpaysdk")) {
                Intent intent = new Intent();
                intent.setComponent(new ComponentName("com.shengpay.smartpos.shengpaysdk", "com.shengpay.smartpos.shengpaysdk.activity.MainActivity"));
                intent.putExtra("appId", getPackageName());
                String barcodeType = null;
                intent.putExtra("barcodeType", barcodeType);
                String amount = null;
                intent.putExtra("amount", amount);
                String orderNoSFT = getIntent().getStringExtra("orderId");
                intent.putExtra("orderNoSFT", "");
                String reserve47 = null;
                intent.putExtra("reserve47", reserve47);
                String priInfo = null;
                intent.putExtra("priInfo", priInfo);
                String priInfo2 = null;
                intent.putExtra("priInfo2", priInfo2);
                String printMerchantInfo = null;
                intent.putExtra("printMerchantInfo", printMerchantInfo);
                String printMerchantInfo2 = null;
                intent.putExtra("printMerchantInfo2", printMerchantInfo2);
                String oldTraceNo = null;
                intent.putExtra("oldTraceNo", oldTraceNo);
                String oldReferenceNo = null;
                intent.putExtra("oldReferenceNo", oldReferenceNo);
                String riseString = null;
                intent.putExtra("riseString", riseString);
                intent.putExtra("transName", "17");
                startActivityForResult(intent, REQUEST_CODE_QUERY_BANK_CARD_TRANSACTION);
            } else
                Toast.makeText(this, "未安装盛付通SDK", Toast.LENGTH_SHORT).show();
        });
        //打印
        dataBinding.ciDetailPrint.setOnClickListener(v -> {
            if (model.coInBean.get().getPay_status() == 3) {
                Toast.makeText(this, "订单未支付,无法打印小票", Toast.LENGTH_SHORT).show();
                return;
            }
            showDialog();
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_QUERY_BANK_CARD_TRANSACTION) {
            Bundle extras = data.getExtras();
            Set<String> set = extras.keySet();
            StringBuilder transactionData = new StringBuilder();
            transactionData.append('{');
            for (String s : set) {
                String str = s + ":" + extras.getString(s) + ",";
                transactionData.append(str);
            }
            transactionData.append('}');
            Log.d(TAG, "transactionData: " + transactionData);
            bankViewModel.uploadTradeInfo(transactionData.toString(), () -> {
                Toast.makeText(this, "状态已同步", Toast.LENGTH_SHORT).show();
            });
        }
    }

    //初始化相关订单
    public void initRelativeOrder() {
        dataBinding.reOrders.setLayoutManager(new LinearLayoutManager(this));
        dataBinding.reOrders.setAdapter(new IAdapter<RelativeBean, ItemRelativeOrderBinding>() {
            @Override
            protected int getLayoutId(int viewType) {
                return R.layout.item_relative_order;
            }

            @Override
            protected void convertListener(@NonNull ItemRelativeOrderBinding binding) {
                binding.setItemNavigator(CollAndInstallDetailActivity.this);
            }

            @Override
            protected int getDataBRId(int itemViewType) {
                return BR.item;
            }

        });
    }

    //打印内容
    private void print() {
        if (model.coInBean.get() != null) {
            CoInDetailBean.DataBean bean = model.coInBean.get();
            List<String> printContent = Objects.requireNonNull(bean).getPrint_array();
            AidlUtil aidlUtil = AidlUtil.getInstance();
            if (Build.MODEL.contains("T2")) {
                String paymentMethod = printContent.get(0);
                String filename = null;
                switch (paymentMethod) {
                    case "0":
                        filename = "icon_alipay.bmp";
                        break;
                    case "1":
                        filename = "icon_union.bmp";
                        break;
                    case "2":
                        filename = "icon_wechat.bmp";
                }
                try {
                    Bitmap bitmap = BitmapFactory.decodeStream(getAssets().open(filename));
                    aidlUtil.printBitmap(bitmap, "0", "2", 0);
                    aidlUtil.printText(printContent.get(1) + '\n', "32", "32",
                            "1", true, false);
                    aidlUtil.printText(printContent.get(2) + '\n', "24", "24",
                            "1", false, false);
                    String paymentMethodAndMore = printContent.get(3);
                    paymentMethodAndMore = paymentMethodAndMore.replace("\\n", "\n");
                    aidlUtil.printText(paymentMethodAndMore, "24", "24",
                            "0", false, false);
                    String collection = printContent.get(6);
                    collection = collection.replace("\\n", "\n");
                    aidlUtil.printText(collection, "24", "24",
                            "0", false, false);
                    String remarks = printContent.get(7);
                    remarks = remarks.replace("\\n", "\n");
                    aidlUtil.printText(remarks, "24", "24",
                            "0", false, false);
                    aidlUtil.printQr(printContent.get(8), "6", "3");
                    String cashierAndPrintingTime = printContent.get(9);
                    cashierAndPrintingTime = cashierAndPrintingTime.replace("\\n", "\n");
                    aidlUtil.printText(cashierAndPrintingTime, "24", "24",
                            "0", false, false);
                    String last = printContent.get(10);
                    last = last.replace("\\n", "\n");
                    aidlUtil.printText(last, "24", "24",
                            "1", false, false);
                    String repeat = printContent.get(12);
                    aidlUtil.printText(repeat + "\n\n", "24", "24",
                            "1", false, false);
                    aidlUtil.cutPaper(null);
                } catch (IOException ex) {
                    Log.e(TAG, null, ex);
                }
            } else {
                aidlUtil.enterPrinterBuffer(true);
                String bitmapType = printContent.get(0);
                //打印支付方式图标
                commenPrint(printContent, aidlUtil, bitmapType);
            }
        }
    }


    //显示打印dialog
    private void showDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this)
                .setTitle("打印小票")
                .setMessage("是否打印小票")
                .setPositiveButton("确认", (dialog, which) -> {
                    dialog.dismiss();
                    print();
                }).setNegativeButton("取消", (dialog, which) -> {
                    dialog.dismiss();
                });
        builder.show();
    }

    @Override
    public void itemClick(RelativeBean item) {
        //如果有关联订单  则根据订单号跳转到相应退款订单
        if (item != null) {
            Intent intent = new Intent(this, CollAndInstallDetailActivity.class);
            intent.putExtra("orderId", item.getOut_trade_no());
            startActivity(intent);
        }
    }
}
